package com.baiyi.homeui.hshomeui.util;

import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SLog {
    private static final String TAG = "SLog";
    public static boolean isCloseLog = false;
    public static boolean saveLog = true;
    private static String path;

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static void d(String msg) {
        if(!isCloseLog) {
            Log.d(TAG,msg);
            if(saveLog){
                saveInFile(TAG,msg);
            }
        }
    }

    public static void i(String TAG,String msg) {
        if(!isCloseLog) {
            Log.d(TAG,msg);
            if(saveLog){
                saveInFile(TAG,msg);
            }
        }
    }

    public static void e(String TAG,String msg) {
        if(!isCloseLog) {
            Log.d(TAG,msg);
            if(saveLog){
                saveInFile(TAG,msg);
            }
        }
    }

    public static void d(String tag,String msg) {
        if(!isCloseLog) {
            int max_str_length = 800 - tag.length();
            //大于4000时
            while (msg.length() > max_str_length) {
                Log.d(tag, msg.substring(0, max_str_length));
                msg = msg.substring(max_str_length);
            }
            if(saveLog){
                saveInFile(tag,msg);
            }
            Log.d(tag,msg);
        }
    }

    private static void saveInFile(String tag,String msg){
        if (TextUtils.isEmpty(path)) {
            path = "sdcard/catchlog/log/home_log.txt";
        }

        File file = new File(path);
        long sizeInBytes = file.length();
        if(sizeInBytes>50*1024*1024){
            file.delete();
        }
        String dateStr = sdf.format(new Date(System.currentTimeMillis()));
        try {
            if (!file.exists()) {
                file.getParentFile().mkdirs();
            }
            //Log.d(TAG,"saveInFile--"+msg);
            FileWriter writer = new FileWriter(file, true);
            writer.append(dateStr+":   "+tag + ": " + msg + "\n");
            writer.close();
        } catch (IOException e) {
            Log.e(TAG, "Failed to write log to file!");
            e.printStackTrace();
        }

    }


}
